//
//  TGLocationTool.m
//  GroupBuy
//
//  Created by wwj on 15/11/19.
//  Copyright © 2015年 wwj. All rights reserved.
//

#import "TGLocationTool.h"
#import <CoreLocation/CoreLocation.h>
#import "TGDataTool.h"

@interface TGLocationTool ()<CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *manager;
@property (strong, nonatomic) TGCityModel *city;
@end

@implementation TGLocationTool

+(instancetype)shareLocationTool{
    static TGLocationTool *locationTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        locationTool = [[TGLocationTool alloc] init];
        
    });
    return locationTool;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        CLLocationManager *manager = [[CLLocationManager alloc] init];
        [manager requestWhenInUseAuthorization];
        manager.delegate = self;
        [manager startUpdatingLocation];
        _manager = manager;
    }
    return self;
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    [manager stopUpdatingLocation];
    CLLocation *location = locations.firstObject;

    [[[CLGeocoder alloc] init] reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = placemarks.firstObject;
        NSString *cityName = [placemark.addressDictionary objectForKey:@"City"];
        
        if (_locationCity == nil) {
            _locationCity = [[TGDataTool shareDataTool] getCityWithName:[cityName substringToIndex:cityName.length -1]];
            _locationCity.position = location.coordinate;
            [TGDataTool shareDataTool].currentCity = _locationCity;
        }
    }];
}


@end
